﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.DirectoryServices;
using System.Threading;

namespace CSP.Package.Controls
{
    public class MetabasePropertyNames
    {// from http://technet2.microsoft.com/WindowsServer/en/Library/271ae19b-853f-4672-b743-5ba126e902db1033.mspx?mfr=true

        //TODO add all Properties

        public const string AuthFlags = "AuthFlags";

        public const string keyType = "keyType";

    }



    [FlagsAttribute()]

    public enum AuthFlags
    {//from http://technet2.microsoft.com/WindowsServer/en/Library/271ae19b-853f-4672-b743-5ba126e902db1033.mspx?mfr=true

        AuthAnonymous = 1,

        AuthBasic = 2,

        AuthNTLM = 4,

        AuthMD5 = 16,

        AuthPassport = 64

    }

    public partial class SimpleCMSPackage : UserControl,IInstallationControl
    {
        public SimpleCMSPackage()
        {
            InitializeComponent();
        }

        #region IInstallationControl Members

        private Installer form;
        public Installer GetForm()
        {
            return form;
        }

        public void SetForm(Installer installer)
        {
            form = installer;
        }


        public static void StartWebsite(int site_id)
        {
            string location = "IIS://localhost/W3SVC/" + site_id.ToString();
            DirectoryEntry entry = new DirectoryEntry(location);
            entry.Invoke("start", new object[] { });
            object status = entry.InvokeGet("Status");
            while ((int)status != 2)
            {
                Thread.Sleep(500);
                status = entry.InvokeGet("Status");
            }

            AuthFlags nAuthFlags = (AuthFlags)(entry.Properties[MetabasePropertyNames.AuthFlags][0]);
            nAuthFlags = nAuthFlags | AuthFlags.AuthAnonymous; //clear anonymous
            nAuthFlags = nAuthFlags | AuthFlags.AuthNTLM; //Add Integrated
            entry.Properties[MetabasePropertyNames.AuthFlags][0] = nAuthFlags;


            entry.CommitChanges();
            entry.Close();


            MessageBox.Show(CSP.Package.labels.CSPInstallInfo_SiteCreated, CSP.Package.labels.CSPInstallInfo_Label, MessageBoxButtons.OK, MessageBoxIcon.Information);


        }

        private bool ValidateInput()
        {
            if (txbPort.Text == string.Empty)
            {
                txbPort.Text = "80";
            }
            try
            {
                int i = Convert.ToInt32(txbPort.Text);
                if (i > 65539)
                {
                    MessageBox.Show(CSP.Package.labels.CspInstallError_PortInteger, CSP.Package.labels.CspInstallError_Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txbPort.Focus();
                    txbPort.Select();
                    return false;
                }
            }
            catch
            {
                MessageBox.Show(CSP.Package.labels.CspInstallError_PortInteger, CSP.Package.labels.CspInstallError_Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
                txbPort.Focus();
                txbPort.Select();
                return false;
            }
            return true;
        }
 

        public bool Next()
        {
            try
            {

                Process proces = new Process();
                proces.StartInfo.FileName = @"csp.simplecms.msi";
                proces.StartInfo.WorkingDirectory = @"SimpleCMS";
                proces.Start();
                proces.WaitForExit();
                if (proces.ExitCode != 0)
                {
                    throw new ApplicationException(CSP.Package.labels.CspInstallError_Unexpected);
                }
                return true;
            }
            catch (Exception ex)
            {
                GetForm().ShowException(ex);
                throw ex;
            }
        }

        public void Previous()
        {
        }

        public void Skip()
        {
        }

        #endregion

        private void btnFolder_Click_1(object sender, EventArgs e)
        {
            if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
                txbPath.Text = folderBrowserDialog1.SelectedPath;

        }

        private void btnCreate_Click(object sender, EventArgs e)
        {

            if (ValidateInput())
            {
                //TODO: SimpleCMSServicePrincipalName
                string serverComment = txbDescription.Text;
                string path = txbPath.Text;
                System.IO.Directory.CreateDirectory(path);
                string serverBindings = string.Format(":{0}:{1}", txbPort.Text, txbHostHeader.Text);
                DirectoryEntry w3svc = new DirectoryEntry("IIS://localhost/w3svc");
                object[] newSite = new object[] { serverComment, new object[] { serverBindings }, path };
                object siteId = (object)w3svc.Invoke("CreateNewSite", newSite);
                
                StartWebsite(Convert.ToInt32(siteId));
            }
        }

        private void SimpleCMSPackage_Load(object sender, EventArgs e)
        {
            TranslateLiterals();
        }


        private void TranslateLiterals()
        {
            richTextBox1.Text = CSP.Package.labels.SimpleCMSPackage_Intro;

            groupBox1.Text = CSP.Package.labels.IISWebSite_GroupBox;

            label5.Text = CSP.Package.labels.Port_Label;
            label6.Text = CSP.Package.labels.HostHeader_Label;
            label2.Text = CSP.Package.labels.Description_Label;
            label1.Text = CSP.Package.labels.Path_Label;

            btnCreate.Text = CSP.Package.labels.Create_Label;
        }

    }
}
